package com.UU.J2EE.PizzaStore.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

public class CreateVerificationServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = null;

		response.setDateHeader("Expires", -1);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Content-Type", "image/jpeg");
		
		//create an image
		BufferedImage image = new BufferedImage(60, 25, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		//set the background
		g.setColor(Color.white);
		g.fillRect(0, 0, 60, 60);
		g.setColor(Color.black);
		g.setFont(new Font(null,Font.BOLD,20));
		//write data to the image
		String num = makeNum();
		request.getSession().setAttribute("verification", num);
		g.drawString(num, 0, 20);
		ImageIO.write(image, "jpg" , response.getOutputStream());
	}
	public String makeNum()
	{
		String chars = "0123456789abcdefghijklmnopqrstuvwxyz";
		String num = null;
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < 4 ; i++)
		{
			sb.append(chars.charAt((int)(Math.random()*36)));
			//System.out.println(sb);
		}
		num = sb.toString();
		return num;
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}
